import 'package:flutter/material.dart';

import '../models.dart';
import '../typedefs.dart';

class AddEditScreen extends StatefulWidget {
  final void Function(Todo) onSave;
  final Todo? todo;
  const AddEditScreen({super.key, required this.onSave, this.todo});
  bool get isEditing => todo != null;
  @override
  State<AddEditScreen> createState() => _AddEditScreenState();
}

class _AddEditScreenState extends State<AddEditScreen> {
  String _task = '';
  String _note = '';
  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('${widget.isEditing ? 'Edit' : 'Add'} TODO')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Form(
          key: formKey,
          child: ListView(
            children: [
              TextFormField(
                initialValue: widget.todo?.task,
                decoration: const InputDecoration(hintText: 'hello task input'),
                onSaved: (newVal) => _task = newVal!,
                validator: (value) =>
                    value!.isEmpty ? 'Please enter a task' : null,
              ),
              TextFormField(
                initialValue: widget.todo?.note,
                maxLines: null,
                minLines: 3,
                keyboardType: TextInputType.multiline,
                decoration: const InputDecoration(hintText: 'additional notes'),
                onSaved: (newValue) => _note = newValue!,
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          final form = formKey.currentState;
          form!.save();
          final isValid = form!.validate();
          if (isValid) {
            // form.save();
            if (widget.isEditing) {
              final updatedTodo = Todo(
                _task,
                id: widget.todo!.id,
                note: widget.todo!.note,
                complete: widget.todo!.complete,
              );
              widget.onSave(updatedTodo);
            } else {
              final newTodo = Todo(_task, note: _note);
              widget.onSave(newTodo);
            }
            Navigator.of(context).pop();
          }
        },
        child: Icon(Icons.check),
      ),
    );
  }
}
